<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-05-11 16:55:00
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-07-21 09:38:04
 * @Description:
 *
-->

<template>
  <div ref="alarmRuleCtn" class="alarm-rule-container">
    <el-row class="header" type="flex" align="middle">
      <span class="name">告警名称</span>
      <el-input
        v-model="ruleName"
        style="width: 170px; margin-left: 10px; margin-right: 20px"
        size="medium"
        class="input"
        placeholder="请输入告警名称"
        clearable
        @clear="clearNameClick('ruleName')"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="medium"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-button size="medium" @click="resetClick">重置</el-button>
      <el-button
        size="medium"
        style="margin-left: auto"
        type="primary"
        icon="el-icon-plus"
        @click="addClick(2)"
      >添加告警规则</el-button>
      <!-- <el-button
        size="medium"
        type="primary"
        plain
        icon="el-icon-plus"
        @click="addClick(1)"
      >添加普通规则</el-button> -->
    </el-row>
    <div class="main">
      <div
        class="grid-wrapper"
        :style="{ 'grid-template-columns': gridColumns.join(' ') }"
      >
        <div
          v-for="(item, index) in list"
          :key="index"
          :class="[
            'grid-item',
            item.alarmLevel === '紧急'
              ? 'urgent'
              : item.alarmLevel === '重要'
                ? 'major'
                : item.alarmLevel === '次要'
                  ? 'secondary'
                  : '',
          ]"
        >
          <div class="top">
            <div class="name">{{ item.ruleName }}</div>
            <img
              class="img edit"
              src="@/assets/imgs/alarm/icon_edit.png"
              alt=""
              @click="editClick(item)"
            />
            <el-popover
              :ref="`popover-delete-grid-${index}`"
              placement="top"
              width="300"
            >
              <p>是否确认删除该规则？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="$refs[`popover-delete-grid-${index}`][0].doClose()"
                >取消</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="deleteClick(item, index)"
                >确定</el-button>
              </div>
              <img
                slot="reference"
                class="img"
                src="@/assets/imgs/alarm/icon_delete.png"
                alt=""
              />
            </el-popover>
          </div>
          <div class="center">
            <div class="row">
              <div class="title">规则设置</div>
              <div class="content">{{ item.ruleExpStr }}</div>
            </div>
            <div v-if="item.intelligentParam" class="row notes">
              <div class="title">备注</div>
              <div class="content">
                {{ getAlarmRuleNotes(item.intelligentParam) }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-row type="flex" justify="end" style="margin-top: 20px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          :current-page.sync="pageNum"
          :total="totalSize"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
    </div>

    <AddNormalDialog
      v-if="showDialog && dialogScene === 1"
      :show.sync="showDialog"
      :is-edit="isEditDialog"
      :info="editInfo"
      @edit-success="editSuccessCallback"
      @add-success="addSuccessCallback"
    />
    <AddIntelligentDialog
      v-if="showDialog && dialogScene === 2"
      :show.sync="showDialog"
      :is-edit="isEditDialog"
      :info="editInfo"
      @edit-success="editSuccessCallback"
      @add-success="addSuccessCallback"
    />
  </div>
</template>

<script>
import pageResize from '@/views/mixin/pageResize.js'
import { getRuleList, deleteRule } from '@/api/cnap/statis-analysis'
import AddNormalDialog from './alarm-rule/AddNormalDialog.vue'
import AddIntelligentDialog from './alarm-rule/AddIntelligentDialog.vue'

export default {
  name: 'AlarmRule',
  components: {
    AddNormalDialog,
    AddIntelligentDialog
  },
  mixins: [pageResize],
  data() {
    return {
      ruleName: '', // 告警名称
      gridColumns: ['1fr', '1fr', '1fr', '1fr'],
      loading: false, // 加载中
      pageSize: 12, // 页size
      pageSizes: [12, 16, 20],
      pageNum: 1, // 页码
      totalSize: 0, // 总数
      list: [], // 列表
      showDialog: false, // 不展示
      dialogScene: 1, // 1-普通告警弹窗 2-智能告警弹窗
      isEditDialog: false,
      editInfo: {}
    }
  },
  created() {},
  mounted() {
    this.computeGridColumns()
    this.initPageData() // 初始化
  },
  methods: {
    /**
     * @description: 获取规则备注
     * @param {*} item
     * @return {*}
     */
    getAlarmRuleNotes(intelligentParam) {
      const info =
        intelligentParam.clusterName + ' | ' + intelligentParam.resType
      if (Array.isArray(intelligentParam.resInfos)) {
        return intelligentParam.resInfos.reduce((pre, cur) => {
          return pre + ' | ' + cur.resName
        }, info)
      }
      return info
    },
    /**
     * @description: 重新布局
     * @return {*}
     */
    resize() {
      this.computeGridColumns()
    },
    /**
     * @description: 计算grid列数
     * @return {*}
     */
    computeGridColumns() {
      const ctnWidth = this.$refs.alarmRuleCtn.clientWidth
      if (ctnWidth > 1200) {
        this.gridColumns = ['1fr', '1fr', '1fr', '1fr']
      } else if (ctnWidth > 820) {
        this.gridColumns = ['1fr', '1fr', '1fr']
      } else if (ctnWidth > 500) {
        this.gridColumns = ['1fr', '1fr']
      }
      this.pageSize = this.gridColumns.length * 3
      this.pageSizes = [
        this.gridColumns.length * 3,
        this.gridColumns.length * 4,
        this.gridColumns.length * 5
      ]
    },
    /**
     * @description: 添加告警规则成功回调
     * @return {*}
     */
    addSuccessCallback() {
      this.$message.success({
        message: '添加告警规则成功！',
        duration: '1500'
      })
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 添加普通告警规则
     * @return {*}
     */
    addClick(scene) {
      this.isEditDialog = false
      this.dialogScene = scene
      this.showDialog = true // 展示
    },
    /**
     * @description: 更新告警规则成功回调
     * @return {*}
     */
    editSuccessCallback() {
      this.$message.success({
        message: '更新告警规则成功！',
        duration: '1500'
      })
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 编辑
     * @param {*} row
     * @return {*}
     */
    editClick(item) {
      this.editInfo = JSON.parse(JSON.stringify(item)) // 获取表单数据
      this.dialogScene = 2
      this.isEditDialog = true // 编辑弹窗
      this.showDialog = true // 展示
    },
    /**
     * @description: 删除
     * @param {*} scope
     * @return {*}
     */
    deleteClick(row, index) {
      // 请求接口
      deleteRule(row.id).then((res) => {
        this.$refs[`popover-delete-grid-${index}`][0].doClose() // 取消popover
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageNum = Math.max(this.pageNum - 1, 1) // 当前页只剩一条数据时 删除后请求上一页
        }
        this.getAlarmRuleList() // 请求数据
      })
    },
    /**
     * @description: size变化
     * @param {*} size
     * @return {*}
     */
    sizeChange(size) {
      this.pageSize = size
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 切换页码
     * @param {*} pageNum
     * @return {*}
     */
    changePage(pageNum) {
      this.pageNum = pageNum
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 清除名称
     * @return {*}
     */
    clearNameClick() {
      this.ruleName = ''
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 重置
     * @return {*}
     */
    resetClick() {
      this.ruleName = ''
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 查询
     * @return {*}
     */
    queryClick() {
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    },
    /**
     * @description: 获取告警规则列表
     * @return {*}
     */
    getAlarmRuleList() {
      // 请求
      getRuleList({
        ruleName: this.ruleName,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
        .then((res) => {
          if (res.data) {
            this.totalSize = res.data.totalSize
            this.list = Array.isArray(res.data.data) ? res.data.data : []
          } else {
            // 数据为空处理
            this.totalSize = 0
            this.list = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 初始化数据
     * @return {*}
     */
    initPageData() {
      this.loading = true
      this.pageNum = 1 // 第一页
      this.getAlarmRuleList() // 请求数据
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.alarm-rule-container {
  .header {
    margin-bottom: 20px;
    .name {
      .textStyle(14px , 400, #4a4a4a);
      line-height: 20px;
    }
  }
  .main {
    .grid-wrapper {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr;
      grid-template-rows: auto;
      grid-column-gap: 20px;
      grid-row-gap: 20px;

      .grid-item {
        box-sizing: border-box;
        padding: 15px;
        background: linear-gradient(213deg, #00c4ff 0%, #0091ff 100%);
        border-radius: 6px;

        &.urgent {
          background: linear-gradient(205deg, #f9b4bd 0%, #f66173 100%);
        }
        &.major {
          background: linear-gradient(213deg, #f6ce01 0%, #f4a93e 100%);
        }
        &.secondary {
          background: linear-gradient(134deg, #44dec5 0%, #4ebcfa 100%);
        }

        .top {
          display: flex;
          align-items: center;

          .name {
            .textStyle(16px, 600, #FFFFFF);
            line-height: 22px;
          }

          .img {
            width: 13px;
            cursor: pointer;

            &.edit {
              margin-left: auto;
              margin-right: 10px;
            }
          }

          /deep/ .el-popover__reference-wrapper {
            display: flex;
            align-items: center;
          }
        }

        .center {
          margin-top: 10px;
          background: #ffffff;
          border-radius: 7px;
          padding: 15px;

          .row {
            display: flex;

            &.notes {
              margin-top: 8px;
            }

            .title {
              min-width: 56px;
              .textStyle(14px, 500, #B9B9B9);
              line-height: 20px;
              margin-right: 20px;
            }
            .content {
              flex: 1;
              .textStyle(14px, 500, #4a4a4a);
              line-height: 20px;
              word-break: break-all;
            }
          }
        }
      }
    }
  }
}
</style>
